class YouthController < ApplicationController
  before_filter :login_required

	layout 'standard'


	def list
		@youth_statuses = YouthStatus.find(:all)
		@youth_groups = YouthGroup.find(:all)
		@regions = Region.find(:all)
		@institutions = Institution.find(:all)
    @data_collectors = DataCollector.find(:all)
		
		sort = case params[:sort]
			when "id" then "youths.id"
			when "status" then "youth_statuses.name"
			when "gender" then "gender"
			when "region" then "regions.name"
			when "yls-score" then "yls_score"
			when "birthdate" then "birthdate"
			when "group" then "youth_groups.name"
			when "institution" then "institutions.name"
			when "comment" then "comment"
			when "id_reverse" then "youths.id DESC"
			when "status_reverse" then "youth_statuses.name DESC"
			when "gender_reverse" then "gender DESC"
			when "region_reverse" then "regions.name DESC"
			when "yls-score_reverse" then "yls_score DESC"
			when "birthdate_reverse" then "birthdate DESC"
			when "group_reverse" then "youth_groups.name DESC"
			when "institution_reverse" then "institutions.name DESC"
			when "comment_reverse" then "comment DESC"
		end
		
		if sort.nil? then sort = "youths.id" end
		
			@youths = Youth.find(:all, :include => ['youth_status', 'youth_group', 'region', 'institution'], :order => sort, :conditions => params[:youth])
		

		if request.xml_http_request?
			render :partial => "youths_list", :layout => false
		end
	end
	
	def new
		@youth = Youth.new
		@regions = Region.find(:all)
	end
	
	def create
		@youth = Youth.new(params[:youth])
    @youth.current_user = current_user

    @youth.save
    if @youth.errors.empty?
      get_changes_saved_text(@youth)
      redirect_to :action => 'edit', :id => @youth.id
    else
      flash_errors(@youth)
      redirect_to :back
    end
	end
	
	def edit
		@youth = Youth.find(params[:id])
		@notes = @youth.youth_notes.reverse
		@data_collections = @youth.data_collections.sort_by{|dc| [dc.target_date]}
	end
	
	def update
		@youth = Youth.find(params[:id])
    @youth.current_user = current_user
		
    @youth.update_attributes(params[:youth])
    
    if (@youth.errors.empty?)
      get_changes_saved_text(@youth)
      redirect_to :action => 'edit', :id => @youth.id
    else
      flash_errors(@youth)
      redirect_to :back
    end
	end

  def delete
    Youth.find(params[:id]).destroy
    flash[:notice] = "Youth destroyed!"
    redirect_to :action => 'list'
  end


  def calculate_statistics
    render :text => "Coming soon!"
  end
end
